package com.a9_lin.www.testormlite.dao;

import android.content.Context;

import com.a9_lin.www.testormlite.bean.Userinfo;
import com.j256.ormlite.dao.Dao;

import java.sql.SQLException;
import java.util.List;

/**
 * Created by macmini on 16/10/25.
 */

public class NewUserInfoDao {

    private Context context;
    private Dao<Userinfo,Integer> userDaoOpe;
    private DatabaseHelper helper;

    private NewWatchDao watchDao;

    public NewUserInfoDao(Context context){
        this.context = context;
        try{
            helper = DatabaseHelper.getHelper(context);
            userDaoOpe = helper.getDao(Userinfo.class);

            watchDao = NewWatchDao.getInstance(context);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private static NewUserInfoDao instance;

    /**
     * 单例获取
     *
     * @param context
     * @return
     */
    public static synchronized NewUserInfoDao getInstance(Context context) {
        context = context.getApplicationContext();
        if (instance == null) {
            synchronized (DatabaseHelper.class) {
                if (instance == null)
                    instance = new NewUserInfoDao(context);
            }
        }

        return instance;
    }

    public void insert(Userinfo userinfo){
        try{
            watchDao.insert(userinfo.getWatch());
            userDaoOpe.create(userinfo);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public boolean delete(Userinfo userinfo){
        try{
             return userDaoOpe.delete(userinfo)==1;
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

    public void update(Userinfo userinfo){
        try{
            userDaoOpe.update(userinfo);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public List<Userinfo> queryAll(){
        try{
            return userDaoOpe.queryForAll();
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public List<Userinfo> queryAllWithWatch(){
        try{
            List<Userinfo> userinfos = userDaoOpe.queryForAll();
            for(int i = 0;i<userinfos.size();i++){
                watchDao.refresh(userinfos.get(i).getWatch());
//                helper.getDao(Watch.class).refresh(userinfos.get(i).getWatch());
            }
            return userinfos;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public void refresh(Userinfo userinfo) throws SQLException {
        userDaoOpe.refresh(userinfo);
        watchDao.refresh(userinfo.getWatch());
    }

}
